//app.js
var config = require('./config');
App({
  onLaunch: function () {
  },
  onShow: function () {

  },
  onHide: function () {

  },
  onError: function () {

  },
  globalData: {
    openid: null,
    userInfo: null,
    myChanged: false
  },
  // lazy loading openid
  getUserOpenId: function (callback) {
    var self = this
    if (self.globalData.openid) {
      callback(null, self.globalData.openid)
    } else {
      wx.login({
        success: function (data) {
          wx.request({
            url: config.login_url,
            data: {
              code: data.code
            },
            success: function (res) {
              self.globalData.openid = res.data
              callback(null, self.globalData.openid)
            },
            fail: function (res) {
              callback(res)
            }
          })
        },
        fail: function (err) {
          callback(err)
        }
      })
    }
  },
  getUserInfo: function (callback) {
    var self = this;
    if (self.globalData.userInfo) {
      callback(null, self.globalData.userInfo)
    } else {
      // 没有登陆先登陆.
      wx.login({
        success: function (res) {
        },
        fail: function (res) {
          callback(res)
        }
      });

      wx.getSetting({
        success: function (res) {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: function (res) {
                self.globalData.userInfo = res.userInfo;
                callback(null, self.globalData.userInfo);
              },
              fail: function (res) {
                callback(res)
              }
            });
          } else {
            wx.authorize({
              scope: 'scope.userInfo',
              success: function (res) {
                wx.getUserInfo({
                  success: function (res) {
                    self.globalData.userInfo = res.userInfo;
                    callback(null, self.globalData.userInfo);
                  },
                  fail: function (res) {
                    callback(res)
                  }
                });
              },
              fail: function (res) {
                callback(res)
              }
            })
          }
        }
      });
    }
  }
})